using System;
using System.Windows.Forms;

namespace dk2Repository.Example
{
	public class NullableDateTimePicker : System.Windows.Forms.DateTimePicker   
	{
		private DateTimePickerFormat _oldFormat = DateTimePickerFormat.Long;
		private string _oldCustomFormat;
		private bool _isNull;

	    public new DateTime Value 
		{
			get {
			    return _isNull ? DateTime.MinValue : base.Value;
			}
	        set 
			{
				if (value == DateTime.MinValue)
				{
                    if (_isNull == false) 
					{
						_oldFormat = this.Format;
						_oldCustomFormat = this.CustomFormat;
                        _isNull = true;
					}

					Format = DateTimePickerFormat.Custom;
					CustomFormat = " ";
				}
				else 
				{
                    if (_isNull) 
					{
						Format = _oldFormat;
						CustomFormat = _oldCustomFormat;
                        _isNull = false;
					}
					base.Value = value;
				}
			}
		}

		protected override void OnCloseUp(EventArgs eventargs)
		{
			if (MouseButtons == MouseButtons.None) 
			{
                if (_isNull) 
				{
					Format = _oldFormat;
					CustomFormat = _oldCustomFormat;
                    _isNull = false;
				}
			}
			base.OnCloseUp (eventargs);
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			base.OnKeyDown (e);

			if (e.KeyCode == Keys.Delete)
				Value = DateTime.MinValue; 
		}
	}
}
